/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * Description: This class handles web service calls associated with hold placement.
 * 
 */

package us.in.lib.acpl.Mobile_ACPL.ws;

import java.io.IOException;
import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Xml;
import us.in.lib.acpl.Mobile_ACPL.SearchResultsTitleDetailActivity;
import us.in.lib.acpl.Mobile_ACPL.context.Mobile_ACPL;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient.RequestMethod;

public class PlaceHoldHandler {
	public static final String PLACE_HOLD_URL = Mobile_ACPL.WS_HOST+"/symws/rest/patron/placeMyHold";
	SearchResultsTitleDetailActivity act;
	String titleID;
	boolean success = false;
	String failureReason = "Error. Item not placed on hold";
	String pickupLibrary;
	SharedPreferences prefs;

	public PlaceHoldHandler(SearchResultsTitleDetailActivity act) {
		this.act = act;

	}

	public void placeHold(String titleID, String pickupLibrary) {

		this.titleID = titleID;
		this.pickupLibrary = pickupLibrary;
		prefs = act.getSharedPreferences("myPrefs",
				Context.MODE_WORLD_WRITEABLE);
		LoginHandler loginHandler = new LoginHandler();
		loginHandler.getNewSessionToken(prefs, act);
		if (prefs.getString("sessionToken", null) != null) {
			new PlaceHoldTask().execute();
		}

	}

	private class PlaceHoldTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Void... arg0) {
			// TODO Auto-generated method stub

			String sessionToken = prefs.getString("sessionToken", null);

			RestClient client = new RestClient(PLACE_HOLD_URL);
			client.AddHeader("x-sirs-clientID", SearchCatalogHandler.CLIENT_ID);
			client.AddParam("sessionToken", sessionToken);
			client.AddParam("titleKey", titleID);
			client.AddParam("pickupLibraryID", pickupLibrary.toUpperCase());

			try {
				client.Execute(RequestMethod.POST);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			String response = client.getResponse();

			XmlPullParser parser = Xml.newPullParser();

			try {
				parser.setInput(new StringReader(response));

				int eventType = parser.next();

				while (eventType != XmlPullParser.END_DOCUMENT) {
					if (eventType == XmlPullParser.START_TAG) {
						String name = parser.getName();
						if (name.equalsIgnoreCase("Fault")) {
							success = false;
						}
						if (name.equalsIgnoreCase("string")) {
							String text = parser.nextText();
							if (text.startsWith("Sorry")) {
								failureReason = "Hold Failed. Hold limit has been reached.";
							} else if (text.startsWith("User")) {
								if(text.contains("BLOCKED")){
									failureReason="Hold failed. Account is blocked.";
								}else if (text.contains("BARRED")){
									failureReason="Hold failed. Account is barred.";
								}else if (text.contains("User already has a hold")){
									failureReason = "You already have a hold on this item.";
								}else{
									failureReason = "Error. Item not placed on hold";
								}
								
							} else {
								failureReason = "Error. Item not placed on hold";
							}
						}
						if (name.equalsIgnoreCase("PlaceMyHoldResponse")) {
							success = true;
							break;
						}
					}
					eventType = parser.next();
				}
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return Boolean.valueOf(success);
		}

		@Override
		protected void onPostExecute(Boolean success) {
			act.handleHoldResult(success, failureReason);
		}
	}
}
